#include "save.h"

#include <QtSql/QSqlQuery>
#include"usermgr.h"
#include<QSqlError>
#include"global.h"

void Save::ConnectSQLite()
{
    qDebug() << "数据库连接：" << UserMgr::GetInstance()->getName();
    DB = QSqlDatabase::addDatabase("QSQLITE", UserMgr::GetInstance()->getName());
    DB.setDatabaseName(FileChattingRecords + UserMgr::GetInstance()->getName() + ".db");
    if (!DB.open()){//连接 没有会自动创建
        qDebug() << "无法打开数据库：";
    }
    query = new QSqlQuery(DB);
    query->exec(QString("PRAGMA table_info(chatting_records)"));
    if(!query->next()){
        qDebug("创建表");
        if (!query->exec(SQLiteStructure)){
            qDebug() << "创建表失败：" << query->lastError().text();
        }
    }
}

void Save::Close()
{
    qDebug() << "关闭数据库";
    // 确保查询已经完成
    if (query) {
        query->finish(); // 确保查询完成
        query->clear();  // 清除查询，以便重新使用
        delete query;
        query = nullptr;
    }

    // 关闭数据库
    if (DB.isOpen()){
        DB.close();
    }
    QSqlDatabase::removeDatabase(UserMgr::GetInstance()->getName());
}

void Save::Add(const long long message_id, const QString& chat_room, const QString& message, const QString& type, const QString& sender_user)
{
    // 安全转义表名
    // QString escapedName = QSqlDatabase::database().driver()->escapeIdentifier(name, QSqlDriver::TableName);

    query->prepare(InsertDataSQL);
    query->addBindValue(message_id);
    query->addBindValue(chat_room);
    query->addBindValue(sender_user);
    query->addBindValue(message);
    query->addBindValue(type);


    bool result = query->exec();
    if (!result) {
        qDebug() << "Error 添加数据:" << query->lastError().text();
    }
}

void Save::Add(const long long message_id, const QString &chat_room, const QString &message, const QString &type, const QString &sender_users, const QDateTime &time)
{
    query->prepare(InsertDataTimeSQL);
    query->addBindValue(message_id);
    query->addBindValue(chat_room);
    query->addBindValue(sender_users);
    query->addBindValue(message);
    query->addBindValue(type);
    query->addBindValue(time);

    bool result = query->exec();
    if (!result) {
        qDebug() << "Error 添加数据:" << query->lastError().text();
    }
}

int Save::QueryChatRecords(const QString &chatRoom, const long long message_id, std::vector<Message>& msg)
{
    query->prepare(QueryChatRecordsSQL);
    query->addBindValue(message_id);
    query->addBindValue(chatRoom);

    if (!query->exec()){
        qDebug() << "QueryChatRecords执行失败: " << query->lastError().text();
        return 0;
    }
    int minId{INT_MAX};

    for (int i = 0; query->next(); i++) {
        if (minId > query->value("message_id").toInt()){
            minId = query->value("message_id").toInt();
        }
        msg[i]._type = query->value("message_type").toString();
        msg[i]._message = query->value("message").toString();
        msg[i]._time = query->value("message_time").toDateTime();
        msg[i]._is_me = query->value("sender_user").toString() == UserMgr::GetInstance()->getName();
    }
    return minId;
}

bool Save::SearchChatRecords(const QString &chatRoom, const QString &key, std::vector<Message> &msg)
{
    query->prepare(SearchChatRecordsSQL);
    query->addBindValue(chatRoom);
    query->addBindValue("%" + key + "%");

    if (!query->exec()){
        qDebug() << "SearchChatRecords执行失败: " << query->lastError().text();
        return false;
    }

    for (int i = 0; query->next(); i++) {
        Message newMessage;
        newMessage._type = query->value("message_type").toString();
        newMessage._message = query->value("message").toString();
        newMessage._time = query->value("message_time").toDateTime();
        newMessage._is_me = query->value("is_me").toInt();
        msg.push_back(newMessage);
    }
    return true;
}

int Save::QueryChatSum(const QString &chat_room)
{
    query->prepare(QueryChatSumSQL);
    query->addBindValue(chat_room);

    if (!query->exec()){
        qDebug() << "QueryChatSum执行失败: " << query->lastError().text();
        return 0;
    }
    query->next();
    return query->value(0).toInt();
}

bool Save::GetChatRoom(std::vector<QString>& list)
{
    if (!query->exec("SELECT DISTINCT chat_room FROM chatting_records;")){
        qDebug() << "GetChatRoom执行失败: " << query->lastError().text();
        return false;
    }

    while (query->next()) {
        list.push_back(query->value(0).toString());
    }

    return true;
}

QDateTime Save::GetMaxRecord(const QString& chat_room, QString& msg)
{
    query->prepare(GetMaxTimeSQL);
    query->addBindValue(chat_room);

    if (!query->exec()){
        qDebug() << "GetMaxRecord执行失败: " << query->lastError().text();
        return QDateTime();
    }
    query->next();
    msg = query->value(1).toString();
    return query->value(0).toDateTime();
}

Save::Save() { }
